package com.wwwarehouse.resource_center.fragment.createobject.creategoods;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.goods.CategoryBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.CategoryEvent;
import com.wwwarehouse.resource_center.eventbus_event.RefreshEvent;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/9/14.
 *         <p/>
 */

public class ChooseCategoryFagment extends TheParentFragment {

    CustomViewPagerInternal viewPager;
    CirclePageIndicator pageIndicator;
    ArrayList<Fragment> fragmentList;
    ElasticScrollView elasticScrollView;
    MyFragmentPagerAdapter adapter;
    int mNum = 8;
    public static final int SELECT_CATEGORY = 0;  //类目查询
    private String parentMetaCategoryUkid = null;
    private String categoryTreeId;
    private CategoryBean.EmptyIdentifierBean emptyIdentifierBean;
    private String ownerUkid;
    private List<CategoryBean.EmptyIdentifierBean> categoryBeen;
    private String title;
    private int level;
    public boolean isFristenter = true;


    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseCategoryFagment)
            mActivity.setTitle(title);
    }

    @Override
    protected int getContentId() {
        return R.layout.fragment_category_parent;
    }

    @Override
    protected void init(View view) {
        elasticScrollView = findView(view, R.id.elastic_scroll);
        viewPager = findView(view, R.id.task_pager);
        pageIndicator = findView(view, R.id.pager_indicator);
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        emptyIdentifierBean = bundle.getParcelable("bean");
        ownerUkid = bundle.getString("ownerUkid");
        level = bundle.getInt("level");
        if (level == 0) {
            level = 1;
        }
        if (emptyIdentifierBean != null) {
            parentMetaCategoryUkid = sp.getValue("ParentMetaCategoryUkid");
            categoryTreeId = sp.getValue("categoryTreeId");
            title = sp.getValue("parentName");
        } else {
            title = getString(R.string.one_level);
            parentMetaCategoryUkid = null;
        }
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    @Override
    protected void loadDatas() {

        httpPost(SELECT_CATEGORY);
        isFristenter = false;
    }

    public void onEventMainThread(Object event) {
        if (event instanceof CategoryEvent && "next".equals(((CategoryEvent) event).getForm())) {
            //进入下级目录
            if (level == Integer.parseInt(((CategoryEvent) event).getMsg().getLevel())) {
                ChooseCategoryFagment chooseCategoryFagment = new ChooseCategoryFagment();
                Bundle bundle = new Bundle();
                bundle.putParcelable("bean", ((CategoryEvent) event).getMsg());
                bundle.putInt("level", Integer.parseInt(((CategoryEvent) event).getMsg().getLevel()) + 1);
                bundle.putString("ownerUkid", ownerUkid);
                sp.putValue("parentName", ((CategoryEvent) event).getMsg().getName());
                sp.putValue("ParentMetaCategoryUkid", ((CategoryEvent) event).getMsg().getMetaCategoryUkid());
                sp.putValue("categoryTreeId", ((CategoryEvent) event).getMsg().getCategoryTreeUkid());
                chooseCategoryFagment.setArguments(bundle);
                pushFragment(chooseCategoryFagment);

            }

        } else if (event instanceof CategoryEvent && "add".equals(((CategoryEvent) event).getForm())) {
            //添加下级目录
            if (level == Integer.parseInt(((CategoryEvent) event).getMsg().getLevel())) {
                GoodsCategoryAddFragment categoryAddFragment = new GoodsCategoryAddFragment();
                Bundle bundle = new Bundle();
                sp.putValue("parentName", ((CategoryEvent) event).getMsg().getName());
                bundle.putParcelable("bean", ((CategoryEvent) event).getMsg());
                bundle.putString("ownerUkid", ownerUkid);
                categoryAddFragment.setArguments(bundle);
                pushFragment(categoryAddFragment);
            }

        } else if (event instanceof RefreshEvent) {
            if ("refresh".equals(((RefreshEvent) event).getMsg())) {
                httpPost(SELECT_CATEGORY);
            }
        } else if (event instanceof CategoryEvent && "finishAdd".equals(((CategoryEvent) event).getForm())) {
            popFragment(); //弹出添加页面
            httpPost(SELECT_CATEGORY);
        }
    }


    @Override
    public void onSuccess(CommonClass commonClass, int what) {

        if (what == SELECT_CATEGORY) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                categoryBeen = JSON.parseArray(commonClass.getData().toString(), CategoryBean.EmptyIdentifierBean.class);
                if (categoryBeen.size() == 0) {
                    popFragment();
                } else {
                    showViewpager(categoryBeen);
                }
            }
        }
    }

    private void showViewpager(List<CategoryBean.EmptyIdentifierBean> caregotyBeen) {
        fragmentList = new ArrayList<>();
        int count = 0;
        if (caregotyBeen.size() > mNum) {
            if ((caregotyBeen.size() - mNum) % mNum == 0) {
                count = (caregotyBeen.size() - mNum) / mNum;
            } else {
                count = (caregotyBeen.size() - mNum) / mNum + 1; // 总共显示多少张卡片
            }
        } else {
            count = 0;
        }

        for (int i = 0; i <= count; i++) {
            CategoryFragment categoryFragment = new CategoryFragment();
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) caregotyBeen);
            bundle.putInt("pos", i);
            bundle.putInt("num", mNum);
            categoryFragment.setArguments(bundle);
            fragmentList.add(categoryFragment);

        }
        if (ChooseCategoryFagment.this.isAdded()) {
            adapter = new MyFragmentPagerAdapter(getChildFragmentManager(), fragmentList);
            viewPager.setAdapter(adapter);
            pageIndicator.setViewPager(viewPager, 0);
        }
    }

    @Override
    public void onReLoad(int code) {
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void httpPost(int selectCategory) {
        if (SELECT_CATEGORY == selectCategory) {
            Map<String, Object> map = new HashMap<>();
            map.put("businessId", ownerUkid);
            String categoryTreeType = "1";
            map.put("categoryTreeType", categoryTreeType);
            if (parentMetaCategoryUkid != null) {
                map.put("parentMetaCategoryUkid", parentMetaCategoryUkid);
                map.put("categoryTreeId", categoryTreeId);
            }
            httpPost(ResourceConstant.SELECT_CATEGORY, map, SELECT_CATEGORY, isFristenter, "");
        }
    }

}
